﻿using BLL;
using Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.入库管理;
using 后整理管理系统.其他窗体;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.新增窗体;
using 纺织贸易管理系统.设置窗体;

namespace 纺织贸易管理系统.报表窗体
{
    public partial class 细码库存 : Form
    {
        private List<JuanHaoTable> juanlist = new List<JuanHaoTable>();
        public 细码库存()
        {
            InitializeComponent();
            CreateGrid.Create(this.Name , gridView2);
            gridView3.OptionsView.EnableAppearanceEvenRow = true;
            gridView3.OptionsView.EnableAppearanceOddRow = true;
            //gridView2.Columns["rq"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";//设置时间显示格式
            gridView2.OptionsCustomization.AllowSort = true;
            cmbmaitou.Items.AddRange ( Tools.获取模板.获取所有模板(PrintPath.唛头模板).ToArray ());
            cmbmaitou.SelectedIndex = 0;
            Query();
            //列出所有仓库名称
            InitStockName();
        }
        /// <summary>
        /// 初始化仓库名称
        /// </summary>
        private void InitStockName()
        {
            comStock.Items.Clear();
            var stockdt = Connect.dbcontext.Ado.GetDataTable("select distinct ckmc from juanhaotable where state=0");
            comStock.Items.Clear();
            comStock.Items.Add("所有仓库");
            foreach (DataRow row in stockdt.Rows)
            {
                comStock.Items.Add((string)row["ckmc"]);
            }
            comStock.SelectedIndex = 0;
        }
        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            Query();
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView2) { formname = this.Name, Obj = new JuanHaoTable () };
            fm.ShowDialog();
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView2);
        }
        private void Query()
        {
            try
            {
                if (txtpagesize.Text == 0.ToString())
                {
                    Tools.ShowMessageBox.ShowErrorBox("每页显示的记录数不能为0；输入无效");
                    txtpagesize.Text = "50";
                    uiPagination1.PageSize = 50;
                    return;
                }
                else
                {
                    uiPagination1.PageSize = txtpagesize.Text.ToInt();
                }
                uiPagination1_PageChanged(null, null, 1, uiPagination1.PageSize);
                var stockname = comStock.Text == "所有仓库" ? string.Empty : comStock.Text;
                var sql = string.Format("select CustomerName as 客户,(select top(1) fullname from lxr where lxr.mc=customername) as 客户全称,SampleName as 品名,ganghao as 缸号,yanse as 颜色,sum(biaoqianmishu*mashu/100) as 合计长度,danwei as 单位,count(*) as 卷数,mashu as 挂码,ReceiptNo as 入库单号 from juanhaotable where Samplename like '%{0}%' and guige like '%{1}%' and kuanhao like '%{2}%' " +
                    "  and ordernum like '%{3}%' and samplenum like '%{4}%' and yanse like '%{5}%' and CustomerName like '%{6}%' and state=0 and DengJI like '%{7}%' and ganghao like '%{8}%' and ckmc like '%{9}%' group by danwei,ganghao,SampleName,CustomerName,yanse,mashu,ReceiptNo order by CustomerName",
                       txtpingming.Text, txtguige.Text, txthuohao.Text, txtOrderNum.Text, txtBianhao.Text, txtsehao.Text, txtkehu.Text, cmbdengji.Text,txtganghao.Text,stockname );
                gridControl3.DataSource = Connect.dbcontext.Ado.SqlQuery<ShowReport>(sql);
            }
            catch(Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("查询的时候发生了错误"+ex.Message);
            }
            //uiProgressIndicator1.Dispose();
        }
        private void 删除卷ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string del = "您确定要把这些\r\n";
            foreach (var i in gridView2.GetSelectedRows())
            {
                //Sunny.UI.UIMessageDialog.ShowSuccessDialog (this, 可发卷BLL.卷删除(gridView2.GetRowCellValue(i, "JuanHao").ToString ()));
                del += "卷号是" + gridView2.GetRowCellValue(i, "JuanHao").ToString() + "  品名是:" + gridView2.GetRowCellValue(i, "SampleName").ToString() + "  颜色是:" + gridView2.GetRowCellValue(i, "yanse").ToString() + "  缸号是:" + gridView2.GetRowCellValue(i, "SampleName").ToString();
                del += "  款号是:" + gridView2.GetRowCellValue(i, "kuanhao").ToString() + "\r\n";
            }
            del += "标识为已出库吗？";
            var res = MessageBox.Show(del, this.Name, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (res == DialogResult.OK)
            {
                var juans = new List<JuanHaoTable>();

                foreach (var i in gridView2.GetSelectedRows())
                {
                    juans.Add(juanlist.FirstOrDefault(x => x.ID == (int)gridView2.GetRowCellValue(i, "ID")));
                    //可发卷BLL.卷删除(gridView2.GetRowCellValue(i, "JuanHao").ToString());
                }
                juans.ForEach(x => x.state = 1);
                try
                {
                    Connect.dbcontext.BeginTran();
                    Connect.dbcontext.Updateable(juans).ExecuteCommand();
                    Connect.dbcontext.CommitTran();
                    Query();
                }
                catch(Exception ex)
                {
                    Connect.dbcontext.RollbackTran();
                    Tools.ShowMessageBox.ShowErrorBox("标识为已发货的时候发送了错误\r\n"+ex.Message);
                }
               
            }
        }

        private void txtpingming_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter )
            {
                Query();
            }
        }

        private void 打印唛头ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView2.CloseEditor();
            var fm = new 打印设置窗体();
            fm.ShowDialog();
            foreach (var s in gridView2.GetSelectedRows())
            {
                gridView2.FocusedRowHandle = s;
                new Tools.打印唛头() { copyies = fm.copyies, PrinterName = fm.printer, userful = PrintModel.Print, moban = PrintPath.唛头模板 + cmbmaitou.Text, juan =JuanHaoTableService.GetOneJuanHaoTable (x=>x.JuanHao==gridView2.GetRowCellValue (s, "JuanHao").ToString ()) }.打印();
            }
            AlterDlg.Show("所有唛头都打印完毕！");
        }

        private void 生成质检单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var juan in juanlist)
            {
                foreach (var chidian in ChiDianTableService.GetChiDianTablelst(x => x.JuanHao == juan.JuanHao))
                {
                    juan.Cidian += "{" + chidian.WeiZhi + "," + chidian.ChiDianName + "}";
                }
            }
            gridControl2.DataSource = juanlist;
            gridControl2.RefreshDataSource();
        }
        private void 编辑报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (后整理管理系统.自定义类.PrintService.CheckPrintDesignAccess())
            {
                Tools.打印检验报告.PrintReport(PrintModel.Design, CreateJuanhao());
            }
        }
        private List<JuanHaoTable > CreateJuanhao()
        {
            var selectjuan = new List<JuanHaoTable>();
            foreach(var row in gridView2.GetSelectedRows())
            {
                selectjuan.Add(juanlist.FirstOrDefault(x => x.ID ==(int) gridView2.GetRowCellValue(row, "ID")));
            }
            return selectjuan;
        }

        private void 预览报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.打印检验报告.PrintReport(PrintModel.Privew, CreateJuanhao());
        }

        private void 打印报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.打印检验报告.PrintReport(PrintModel.Print, CreateJuanhao());
        }

        private void 导出明细ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportFile.导出到文件(gridControl2, "打卷报表");
        }
        private void 打印编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintList(PrintModel.Design);
        }
        private void PrintList(PrintModel useful)
        {
            new Tools.打印清单码单()
            {
                danjuTable = new DanjuTable() ,
                danjumingxitables = new List<danjumingxitable>(),
                danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName ="gridView1" },
                juanHaoTables =SelectHelper.CreatJuanhao (gridView2),
                mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = "gridView1" },
                JuanInfo = new Tools.FormInfo { FormName = "打卷报表", GridviewName = gridView2.Name }
            }.Print(PrintPath.报表模板 + "\\清单码单.frx", useful );
        }

        private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintList(PrintModel.Privew );
        }

        private void gridView2_Click(object sender, EventArgs e)
        {
            if (gridView2.FocusedRowHandle >= 0)
            {
                gridControl1.DataSource = ChiDianTableService.GetChiDianTablelst(x => x.JuanHao == gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "JuanHao").ToString());
            }
        }

        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            this.ShowWaitForm("正在查询，请等待.............");
            int totalnum = 0;
            int totalpage = 0;
            var stockname = comStock.Text == "所有仓库" ? string.Empty : comStock.Text;
            if (checkBox1.Checked)
            {
                juanlist = Connect.dbcontext.Queryable<JuanHaoTable>().Where(x => x.SampleName.Contains(txtpingming.Text) && x.guige.Contains(txtguige.Text) && x.GangHao.Contains(txtganghao.Text) && x.kuanhao.Contains(txthuohao.Text)
                && x.yanse.Contains(txtsehao.Text) && x.CustomerName.Contains(txtkehu.Text) && x.SampleNum.Contains(txtBianhao.Text) && x.OrderNum.Contains(txtOrderNum.Text) && x.Danhao ==string.Empty && x.DengJI.Contains(cmbdengji.Text) && x.Ckmc.Contains(stockname)).OrderByDescending(x => x.ID).ToPageList(pageIndex, count, ref totalnum, ref totalpage);
            }
            else
            {
                juanlist = Connect.dbcontext.Queryable<JuanHaoTable>().Where(x => x.SampleName.Contains(txtpingming.Text) && x.guige.Contains(txtguige.Text) && x.GangHao.Contains(txtganghao.Text) && x.kuanhao.Contains(txthuohao.Text)
                 && x.yanse.Contains(txtsehao.Text) && x.CustomerName.Contains(txtkehu.Text) && x.SampleNum.Contains(txtBianhao.Text) && x.OrderNum.Contains(txtOrderNum.Text) && x.state == 0 && x.DengJI.Contains(cmbdengji.Text) && x.Ckmc.Contains(stockname)).OrderByDescending(x => x.ID).ToPageList(pageIndex, count, ref totalnum, ref totalpage);
            }
            uiPagination1.TotalCount = totalnum;
            gridControl2.DataSource = juanlist;

            this.HideWaitForm();
        }
       
        private void 生成出库单ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                var stocks = CreateStocks();
                if (stocks != null)
                {
                    MainForm.mainform.AddMidForm(new 销售发货单() { InitJuans = SelectHelper.CreatJuanhao(gridView2), stockTables = stocks, useful = FormUseful.新增 });
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("创建发货单的时候发送了错误:" + ex.Message);
            }

        }
        //生成选中的库存信息
        private List<StockTable> CreateStocks()
        {
            if (gridView2.GetSelectedRows().Length == 0)
            {
                Tools.ShowMessageBox.ShowErrorBox("没有任何布料被选中！\r\n生成失败");
                return null;
            }
            var juans = SelectHelper.CreatJuanhao(gridView2);
            ///不同客户不允许开单
            if (juans.Select(x => x.CustomerName).Distinct().Count() > 1)
            {
                Tools.ShowMessageBox.ShowErrorBox("所选布料归属为两个或两个以上客户！\r\n生成失败");
                return null;
            }
            //检查是否在两个不同仓库
            if (juans.Select(x => x.Ckmc).Distinct().Count() > 1)
            {
                Tools.ShowMessageBox.ShowErrorBox("所选布料归属为两个或两个以上仓库！\r\n生成失败");
                return null;
            }
            var stocks = new List<StockTable>();
            foreach (var LotNum in juans.Select(x => x.GangHao).Distinct().ToList())
            {
                var juan = juans.First(x => x.GangHao == LotNum);
                var stock = StockTableService.GetOneStockTable(x => x.PM == juan.SampleName && x.GH == juan.GangHao && x.YS == juan.yanse && x.CustomName == juan.CustomerName && x.RKDH == juan.ReceiptNo && x.CKMC == juan.Ckmc);
                if (stock.ID == 0)
                {
                    //已经出库的信息不能再次出库
                    Tools.ShowMessageBox.ShowErrorBox("生成发货单的时候检查到库存信息已经没有的布料！\r\n缸号是" + stock.GH + "\r\n生成失败");
                    Query();
                    return null;
                }
                else
                {
                    stocks.Add(stock);
                }
            }
            return stocks;
        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                var reports = gridControl3.DataSource as List<ShowReport>;
                var ganghao = gridView3.GetRowCellValue(gridView3.FocusedRowHandle, "缸号").ToString ();
                var customname = gridView3.GetRowCellValue(gridView3.FocusedRowHandle, "客户").ToString ();
              //var r=  reports.First(x => x.缸号 == ganghao && x.客户 == customname);
                var juans = Connect.dbcontext.Queryable<JuanHaoTable>().Where(x => x.GangHao == ganghao && x.CustomerName == customname&&x.state==0).ToList();
                if(juans.Count >0)
                {
                    new 入库信息() { Danhao = juans[0].ReceiptNo }.ShowDialog();
                }
            }
            catch(Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox(ex.Message);
            }
        }
        /// <summary>
        /// 把清库的标识为灰色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void gridView2_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (gridView2.GetRow(e.RowHandle) == null)
            {
                return;
            }
            else
            {
                //获取所在行指定列的值
                int state =(int )gridView2.GetRowCellValue(e.RowHandle, "state");

                //比较指定列的状态
                if (state == 1)
                {
                    e.Appearance.BackColor = Color.NavajoWhite;//设置此行的背景颜色
                }
            }
        }

        private void 退回仓库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var juans = SelectHelper.CreatJuanhao(gridView2);
            if(juans.Where(x=>x.state ==0).Count ()>0)
            {
                Tools.ShowMessageBox.ShowErrorBox("选择的卷包含了还在库的！退回失败");
                return;
            }
            juans.ForEach(x => x.state = 0);
            try
            {
                Connect.dbcontext.BeginTran();
                Connect.dbcontext.Updateable(juans).ExecuteCommand();
                Connect.dbcontext.CommitTran();
            }
            catch(Exception ex)
            {
                Connect.dbcontext.RollbackTran();
                Tools.ShowMessageBox.ShowErrorBox("退回的时候发送了错误！" + ex.Message);
            }
        }

        private void 生成退仓单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var stocks = CreateStocks();
                if (stocks != null)
                {
                    MainForm.mainform.AddMidForm(new 来货退仓单() { InitJuans = SelectHelper.CreatJuanhao(gridView2), stockTables = stocks, Useful = FormUseful.新增 });
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("创建发货单的时候发送了错误:" + ex.Message);
            }
        }

        private void 导出汇总表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportFile.导出到文件(gridControl3, "细码库存表");
        }

        private void 修改信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var juans = SelectHelper.CreatJuanhao(gridView2);
                if (juans.Count == 0)
                {
                    Tools.ShowMessageBox.ShowErrorBox("没有任何布料被选中！\r\n修改失败");
                    return;
                }
                var fm = new 修改信息(juans);
                fm.ShowDialog();
                gridControl2.RefreshDataSource();
            }
            catch(Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("修改信息的时候发生了错误！\r\n"+ex.Message);
            }
        }
    }
}
